/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package com.jjsoft.celularessuc.gco.ui;

import com.jjsoft.celularessuc.gco.mdl.Usuario;
import com.jjsoft.celularessuc.gco.neg.UsuarioManager;
import com.jjsoft.celularessuc.gco.util.UsuarioValidatorException;
import com.jjsoft.celularessuc.gco.util.configuraciones;
import java.awt.GridLayout;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JPasswordField;
import javax.swing.JTextField;
import javax.swing.table.DefaultTableModel;

/**
 *
 * @author Johnny
 */
public class VUsuarios extends javax.swing.JFrame {

    /**
     * Creates new form VUsuarios
     */
    List<Usuario> listaUsuarios;
    UsuarioManager um = new UsuarioManager();
    DefaultTableModel modelo;
    JPanel userPanel = new JPanel();

//Labels for the textfield components        
    JLabel usernameLbl = new JLabel("Password:");
    JLabel passwordLbl = new JLabel("Password:");

    JPasswordField passwordFld1 = new JPasswordField();
    JPasswordField passwordFld2 = new JPasswordField();

    public VUsuarios() {
        initComponents();
        this.listaUsuarios = um.listaUsuarios();
        cargarDatos();
        this.cmdBuscar.setVisible(false);
        userPanel.setLayout(new GridLayout(2, 2));

//Labels for the textfield components        
//Add the components to the JPanel        
        userPanel.add(usernameLbl);
        userPanel.add(passwordFld1);
        userPanel.add(passwordLbl);
        userPanel.add(passwordFld2);
    }

    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jLabel1 = new javax.swing.JLabel();
        jScrollPane1 = new javax.swing.JScrollPane();
        dtgUsuarios = new javax.swing.JTable();
        cmdEliminar = new javax.swing.JButton();
        cmdNuevo = new javax.swing.JButton();
        cmdBuscar = new javax.swing.JButton();
        cmdCambiarClave = new javax.swing.JButton();

        setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);

        jLabel1.setFont(new java.awt.Font("Tahoma", 1, 14)); // NOI18N
        jLabel1.setText("ADMINISTRACION DE USUARIOS");

        dtgUsuarios.setModel(new javax.swing.table.DefaultTableModel(
            new Object [][] {
                {},
                {},
                {},
                {}
            },
            new String [] {

            }
        ));
        dtgUsuarios.setSelectionMode(javax.swing.ListSelectionModel.SINGLE_SELECTION);
        jScrollPane1.setViewportView(dtgUsuarios);

        cmdEliminar.setIcon(new javax.swing.ImageIcon(getClass().getResource("/img/delete.png"))); // NOI18N
        cmdEliminar.setText("Eliminar");
        cmdEliminar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                cmdEliminarActionPerformed(evt);
            }
        });

        cmdNuevo.setIcon(new javax.swing.ImageIcon(getClass().getResource("/img/new.png"))); // NOI18N
        cmdNuevo.setText("Nuevo");
        cmdNuevo.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                cmdNuevoActionPerformed(evt);
            }
        });

        cmdBuscar.setText("jButton1");
        cmdBuscar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                cmdBuscarActionPerformed(evt);
            }
        });

        cmdCambiarClave.setIcon(new javax.swing.ImageIcon(getClass().getResource("/img/edit21.png"))); // NOI18N
        cmdCambiarClave.setText("Asignar Nueva Clave");
        cmdCambiarClave.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                cmdCambiarClaveActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(layout.createSequentialGroup()
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addGroup(layout.createSequentialGroup()
                                .addComponent(cmdNuevo)
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                .addComponent(cmdEliminar)
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                .addComponent(cmdCambiarClave))
                            .addGroup(layout.createSequentialGroup()
                                .addGap(56, 56, 56)
                                .addComponent(jLabel1)
                                .addGap(45, 45, 45)
                                .addComponent(cmdBuscar, javax.swing.GroupLayout.PREFERRED_SIZE, 16, javax.swing.GroupLayout.PREFERRED_SIZE)))
                        .addGap(0, 0, Short.MAX_VALUE))
                    .addComponent(jScrollPane1, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.PREFERRED_SIZE, 0, Short.MAX_VALUE))
                .addContainerGap())
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel1)
                    .addComponent(cmdBuscar))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 147, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                    .addComponent(cmdNuevo, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                    .addComponent(cmdEliminar, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                    .addComponent(cmdCambiarClave, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
                .addContainerGap(22, Short.MAX_VALUE))
        );

        setSize(new java.awt.Dimension(397, 292));
        setLocationRelativeTo(null);
    }// </editor-fold>//GEN-END:initComponents

    private void cmdNuevoActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_cmdNuevoActionPerformed
        // TODO add your handling code here:
        new VNuevoUsuario(cmdBuscar).setVisible(true);
    }//GEN-LAST:event_cmdNuevoActionPerformed

    private void cmdEliminarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_cmdEliminarActionPerformed
        // TODO add your handling code here:
        int i = this.dtgUsuarios.getSelectedRow();
        if (i >= 0) {
            String nick = (String) this.dtgUsuarios.getValueAt(i, 0);
            Usuario usu = um.buscarPorNombre(nick);
            try {
                if (nick.equals(configuraciones.getInstance().getUsuario().getNick())) {
                    JOptionPane.showMessageDialog(this.rootPane, "No se puede borrar su propio usuario");
                } else if (JOptionPane.showConfirmDialog(this.rootPane, "Esta seguro de eliminar el usuario?", "Eliminar Usuario", 0, 3) == 0) {
                    usu.setEstado(1);
                    usu.setPassword(null);
                    um.editarUsuario(usu);
                    this.modelo.removeRow(i);
                }
            } catch (Exception e) {
                JOptionPane.showMessageDialog(this.rootPane, "Error desconicido al eliminar");
            }
        }
    }//GEN-LAST:event_cmdEliminarActionPerformed

    private void cmdBuscarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_cmdBuscarActionPerformed
        // TODO add your handling code here:
        this.listaUsuarios = this.um.listaUsuarios();
        cargarDatos();
    }//GEN-LAST:event_cmdBuscarActionPerformed

    private void cmdCambiarClaveActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_cmdCambiarClaveActionPerformed
        // TODO add your handling code here:
        if (dtgUsuarios.getSelectedRow() != -1) {
            String nick = (String) this.dtgUsuarios.getValueAt(dtgUsuarios.getSelectedRow(), 0);
            Usuario usu = um.buscarPorNombre(nick);
            int input = JOptionPane.showConfirmDialog(null, userPanel, "Ingrese el usuario y password de administrador:", JOptionPane.OK_CANCEL_OPTION, JOptionPane.PLAIN_MESSAGE);
            if (input == 0) {
                if (passwordFld1.getText().equals(passwordFld2.getText())) {
                    usu.setPassword(passwordFld1.getText());
                    try {
                        um.editarUsuario(usu);
                        JOptionPane.showMessageDialog(rootPane, "Operación realizada correctamente", "Asignar Nueva Clave", JOptionPane.INFORMATION_MESSAGE);
                    } catch (UsuarioValidatorException ex) {
                        Logger.getLogger(VUsuarios.class.getName()).log(Level.SEVERE, null, ex);
                    }
                } else {
                    JOptionPane.showMessageDialog(rootPane, "Asegúrese de ingresar 2 veces la misma clave", "Asignar Nueva Clave", JOptionPane.ERROR_MESSAGE);
                }
                passwordFld1.setText("");
                passwordFld2.setText("");
            }
        }
    }//GEN-LAST:event_cmdCambiarClaveActionPerformed

    /**
     * @param args the command line arguments
     */
    public static void main(String args[]) {
        /* Set the Nimbus look and feel */
        //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
        /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
         * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html 
         */
        try {
            for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
                if ("Nimbus".equals(info.getName())) {
                    javax.swing.UIManager.setLookAndFeel(info.getClassName());
                    break;
                }
            }
        } catch (ClassNotFoundException ex) {
            java.util.logging.Logger.getLogger(VUsuarios.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (InstantiationException ex) {
            java.util.logging.Logger.getLogger(VUsuarios.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (IllegalAccessException ex) {
            java.util.logging.Logger.getLogger(VUsuarios.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (javax.swing.UnsupportedLookAndFeelException ex) {
            java.util.logging.Logger.getLogger(VUsuarios.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        }
        //</editor-fold>

        /* Create and display the form */
        java.awt.EventQueue.invokeLater(new Runnable() {
            public void run() {
                new VUsuarios().setVisible(true);
            }
        });
    }

    private void cargarDatos() {
        this.modelo = new DefaultTableModel();
        String[] identificadores = {"Nick", "Rol"};
        this.modelo.setColumnIdentifiers(identificadores);
        for (int i = 0; i < this.listaUsuarios.size(); i++) {
            String rol;
            if (((Usuario) this.listaUsuarios.get(i)).getRol().intValue() == 0) {
                rol = "Administrador";
            } else if (listaUsuarios.get(i).getRol() == 1) {
                rol = "Administrador Sucursal";
            } else {
                rol = "Vendedor";
            }
            String[] articulo = {((Usuario) this.listaUsuarios.get(i)).getNick(), rol};
            this.modelo.addRow(articulo);
        }

        this.dtgUsuarios.setModel(this.modelo);
    }
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton cmdBuscar;
    private javax.swing.JButton cmdCambiarClave;
    private javax.swing.JButton cmdEliminar;
    private javax.swing.JButton cmdNuevo;
    private javax.swing.JTable dtgUsuarios;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JScrollPane jScrollPane1;
    // End of variables declaration//GEN-END:variables
}
